﻿using System;
using System.Web;
using System.Security.Cryptography.X509Certificates;
using System.Security.Cryptography;
using System.Text;

public class Sign : IHttpHandler
{

    private string certPath;
    private static Object objLock = new object();
    public void ProcessRequest(HttpContext context)
    {

        context.Response.ContentType = "text/plain";
        certPath = context.Request.PhysicalApplicationPath + "TESTMERCHANT.p12";
        context.Response.ContentType = "text/xml; charset=utf-8";
        Transaction tran = new Transaction();
        tran.type = "PurchaseAdvice.MARsp";    //转到配置文件读取，或者参数传递
        try
        {
            var form = context.Request.Form;
            var type = typeof(Transaction);
            foreach (var key in form.AllKeys)
            {
                var property = type.GetProperty(key);
                if (property != null)
                {
                    property.SetValue(tran, form[key], null);

                }
            }
            String str = tran.submitTime + tran.orderId + tran.transAmount + tran.currency + tran.terminalId + tran.country + tran.merchantId + tran.merchantName;

            tran.senderSignature = toSign(str);


            context.Response.Write(GenerateXML(tran));
            string s = genSoCode();
        }
        catch
        {
            context.Response.Write("ERROR:");
        }



    }

    ///// <summary>
    ///// 生成订单号，订单号=年数后2位+月数2位+天2位+五位自增数（不够补0）；
    ///// </summary>
    ///// <returns></returns>
    //private String GenerateOrderId(String merchantId)
    //{
    //    if (String.IsNullOrEmpty(merchantId))
    //    {
    //        return "缺少商户号";
    //    }
    //    Object obj = new Object();
    //    lock (obj)
    //    {
    //        String last5MerId = merchantId.Substring(merchantId.Length - 5);
    //        DateTime date = new DateTime();
    //        String font4 = date.ToString("yyMM");
    //        String last7 = date.ToString("dd") + "00001";

    //        String result = font4 + last5MerId + last7;
    //        return result;
    //    }
    //}




    private String GenerateXML(Transaction tran)
    {
        StringBuilder sb = new StringBuilder();
        if (tran != null)
        {
            sb.Append("<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\" ?>");
            sb.Append("<cupMobile version=\"1.01\" application=\"ALL\">");
            sb.AppendFormat("<transaction type=\"{0}\">", tran.type);
            sb.AppendFormat("<submitTime>{0}</submitTime>", tran.submitTime);
            sb.AppendFormat("<order id=\"{0}\">{1}</order>", tran.orderId, tran.order);
            sb.AppendFormat("<transAmount>{0}</transAmount>", tran.transAmount);
            sb.AppendFormat("<terminal id=\"{0}\" />", tran.terminalId);
            sb.AppendFormat("<merchant name=\"{0}\" id=\"{1}\" /> ", tran.merchantName, tran.merchantId);
            sb.Append("</transaction>");
            sb.AppendFormat("<senderSignature>{0}</senderSignature>", tran.senderSignature);
            sb.Append("</cupMobile>");
        }
        return sb.ToString();
    }

    public bool IsReusable
    {
        get
        {
            return false;
        }
    }


    /// <summary>
    /// 长度15位 日期6位+9位
    /// 订单号=yyMMdd+9位自增数；
    /// </summary>
    /// <returns></returns>
    public String genSoCode()
    {


        lock (objLock)
        {
            DateTime date = DateTime.Now;
            String datePart = date.ToString("yyMMdd");


        }
        //final long ALL=36*36*36*36L;
        //final long ALL3=36*36*36L;
        //String datePart = DateTime.getSomeDate(processDate).substring(3);
        //String orderIdxPart = String.valueOf(soIndex%10);// modified by sunlingfei@2010-08-12 orderIdxPart shorted into one digital
        //String strEndUserId = "0" + endUserId.toString();
        //String uidPart = (strEndUserId).substring(strEndUserId.length() - 2);

        //// So newstSo = soDao.getNewstOrderByCodePattern(datePart + orderIdxPart
        //// + uidPart + "____");
        //// String alphaStr = "0001";
        //// if (newstSo != null){
        //// alphaStr =
        //// AlphaHexadecimalUtil.increaseAlphaString(newstSo.getOrderCode().
        //// substring(8));
        //// }

        ////String alphaStr = AlphaHexadecimalUtil.parseLong(this.userorderdao.getNewestOrderCodeSeq()%all, 4);
        //long lTmp = this.userorderdao.getNewestOrderCodeSeq(); //new algorithm for alphaStr provided by SunJun @2010-12-09.
        //if(lTmp<0) lTmp=(lTmp+1)*-1;//防止负数
        //long lCode=(Math.abs(lTmp%(ALL-ALL3-1))+(ALL3+1))%ALL;//保证有且仅有4位
        //String alphaStr = Long.toString(lCode, 36).toUpperCase();//转化为36进制
        //return datePart + orderIdxPart + uidPart + alphaStr;
        return System.Guid.NewGuid().ToString();
    }




    ///签名
    public string toSign(string str)
    {

        X509Certificate2 x509_2 = new X509Certificate2(certPath, "1");
        SHA1 sha1 = new SHA1CryptoServiceProvider();
        byte[] hashbytes = sha1.ComputeHash(Encoding.UTF8.GetBytes(str)); //对要签名的数据进行哈希 
        RSAPKCS1SignatureFormatter signe = new RSAPKCS1SignatureFormatter();
        signe.SetKey(x509_2.PrivateKey); //设置签名用到的私钥 
        signe.SetHashAlgorithm("SHA1"); //设置签名算法 
        byte[] reslut = signe.CreateSignature(hashbytes);
        return byte2hex(reslut);
    }

    public string byte2hex(byte[] b)
    {
        string hs = "";
        string stmp = "";
        for (int i = 0; i < b.Length; i++)
        {
            stmp = b[i].ToString("x");
            if (stmp.Length == 1)
            {
                hs += "0" + stmp;
            }
            else
            {
                hs += stmp;
            }
        }
        return hs;

    }

}